/*
 * Copyright 2016 jeasonlzy(廖子尧)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jiuyin.dianjing.api.server;

import android.content.Context;
import android.content.Intent;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.google.gson.Gson;
import com.jiuyin.dianjing.BuildConfig;
import com.jiuyin.dianjing.api.data.BasicResponseBean;
import com.jiuyin.dianjing.api.data.BasicResponseJson;
import com.jiuyin.dianjing.api.interfaces.ApiCancelRequestCallback;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.interfaces.ProgressDialogCallback;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.util.LogUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okrx2.adapter.ObservableResponse;

import org.json.JSONObject;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.jiuyin.dianjing.api.constant.ApiConstant.RESULT_FAIL;
import static com.jiuyin.dianjing.api.constant.ApiConstant.RESULT_NO_DATA;
import static com.jiuyin.dianjing.api.constant.ApiConstant.RESULT_OK;
import static com.jiuyin.dianjing.api.constant.ApiConstant.RESULT_RE_LOGIN;
import static com.jiuyin.dianjing.constant.AppConstant.ACTION_NEED_LOGIN;

/**
 * 重新封装的网络请求
 */

public final class ServerApi {
    private static final Gson gson = new Gson();

    /**
     * @param url                    请求地址
     * @param jsonObject             请求参数
     * @param cacheMode              缓存类型
     * @param apiResultCallback      回调结果
     * @param progressDialogCallback 进度
     */
    public static void post(String url, JSONObject jsonObject, CacheMode cacheMode, ProgressDialogCallback progressDialogCallback,
                            ApiCancelRequestCallback apiCancelRequestCallback, ApiResultCallback apiResultCallback) {
        url = BuildConfig.SERVER_ADDRESS + url;
        PostRequest<String> postRequest = OkGo.post(url);
        if (null != jsonObject) {
            postRequest.upJson(jsonObject);
            LogUtil.log("post params = " + jsonObject.toString());
        }
        if (null != cacheMode) {
            postRequest.cacheMode(cacheMode);
        }
        postRequest
                .converter(new StringConvert())
                .adapt(new ObservableResponse<>())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (null != progressDialogCallback) {
                        progressDialogCallback.showProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<String>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if (null != apiCancelRequestCallback) {
                            apiCancelRequestCallback.addDis(d);
                        }
                    }

                    @Override
                    public void onNext(@NonNull Response<String> response) {
                        String result = response.body();
                        LogUtil.log("post onNext result = " + result);
                        if (null != apiResultCallback) {
                            try {
                                BasicResponseBean basicResponseBean = gson.fromJson(result, BasicResponseBean.class);
                                LogUtil.log("post = onNext basicResponseBean " + basicResponseBean.toString());
                                if (RESULT_OK == basicResponseBean.getCode()) {
                                    BasicResponseJson basicResponseJson = gson.fromJson(result, BasicResponseJson.class);
                                    apiResultCallback.onSuccess(basicResponseJson.getData());
                                } else if (RESULT_FAIL == basicResponseBean.getCode()) {
                                    apiResultCallback.onFail(basicResponseBean.getMsg());
                                } else if (RESULT_RE_LOGIN == basicResponseBean.getCode()) {
                                    Context context = HelperApplication.getContext();
                                    LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ACTION_NEED_LOGIN));
                                } else if (RESULT_NO_DATA == basicResponseBean.getCode()) {
                                    apiResultCallback.onFail(basicResponseBean.getMsg());
                                }
                            } catch (Exception e) {
                                onError(e);
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (null != apiResultCallback) {
                            apiResultCallback.onError(e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (null != progressDialogCallback) {
                            progressDialogCallback.dismissProgressDialog();
                        }
                    }
                });
    }
}